import requests
import json
import getpass


class Webapi():
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.loginurl = loginurl
        self.sshkeyUrl = sshkeyUrl

    @property
    def get_token(self):
        """
        获取token
        """
        Data = {
            "username": self.username,
            "password": self.password
        }
        try:
          res = requests.post(self.loginurl, Data)
          if res.status_code==200:
            print(res.json())
            if 'token' in res.json()['data']:
              token = res.json()['data']['token']
            else:
              token = "未获得token"
          else:
            print(res.status_code)
        except Exception as e:
          token = False
          print(e)
        return token

    def getManageKey(self):
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Token " + self.get_token
        }

        try:
            response = requests.get(
                self.sshkeyUrl, headers=headers)
            # resone = self._formatResponseOne(response)
            res = response.json()['data']
            return res[0]
        except Exception as e:
            error_msg = 'Get Manage Key Failed ：{}'.format(str(e))
            raise ValueError(error_msg)


if __name__ == '__main__':
    loginurl = "http://10.88.0.157/api/oauth/login1"
    sshkeyUrl = "http://10.88.0.157/api/cmdb/sshkey"

    username = "databackup"
    password = getpass.getpass("请输入%s密码:" % username)

    req = Webapi(username, password)
    req.get_token

    # print(req.headers())
    # print(req.getManageKey())

